//
//  SCAPageControl.m
//  Staff
//
//  Created by caiyao on 2/2/15.
//
//

#import "SCAPageControl.h"

@implementation SCAPageControl

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        buttons = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)setCurrentPage:(NSInteger)page {
    _currentPage = page;
    for (int i = 0; i < self.numberOfPages; i++) {
        UIButton* button = [buttons objectAtIndex:i];
        if (i == page) {
            [button setImage:[UIImage imageNamed:@"PageControlSelected"] forState:UIControlStateNormal];
        }
        else {
            [button setImage:[UIImage imageNamed:@"PageControlDisselected"] forState:UIControlStateNormal];
        }
    }
}

- (void)setNumberOfPages:(NSInteger)numberOfPages {
    _numberOfPages = numberOfPages;
    CGSize size;
    size.height = 34.5;
    size.width = 34.5;
    NSLog(@"%f",(self.bounds.size.width - (2*self.numberOfPages-1)*size.width));
    float leftMargin = (self.bounds.size.width - (2*self.numberOfPages-1)*size.width)/2.0f;
    for (int i = 0; i < numberOfPages; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = (NSInteger)i;
        button.frame = CGRectMake(leftMargin+i*size.width*2, 0,
                   size.width,size.height);
        if (i == 0) {
            [button setImage:[UIImage imageNamed:@"PageControlSelected"] forState:UIControlStateNormal];
        } else {
            [button setImage:[UIImage imageNamed:@"PageControlDisselected"] forState:UIControlStateNormal];
        }
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        [buttons addObject:button];
    }
}

- (void)buttonClick:(id)sender {
    NSInteger index = [(UIButton *)sender tag];
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectedPageAtIndex:)]) {
        [self.delegate selectedPageAtIndex:index];
    }
}

@end
